package com.generator.module.service;

import com.generator.module.entity.Student;
import com.generator.module.mapper.StudentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class StudentService {

    @Resource
    private StudentMapper studentMapper;

    public Student getById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return studentMapper.getById(id);
    }

    public Student extractById(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        }
        return studentMapper.extractById(id);
    }

    public int insert(Student student) {
        return studentMapper.insert(student);
    }

    public int update(Student student) {
        return studentMapper.update(student);
    }

    public int delete(Long id) {
        if (id == null) {
            throw new RuntimeException("Id cannot be null or empty");
        } else {
            if (getById(id) == null) {
                throw new RuntimeException("Student not found");
            }
        }
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        return studentMapper.delete(id, timeStamp);
    }

    public Long edit(
                String name,
                Byte gender,
                Long id
    ) throws RuntimeException {
        int timeStamp = (int) (System.currentTimeMillis() / 1000);
        Student student =new Student();

                student.setName(name);
                student.setGender(gender);

        student.setIsDeleted(1);

        if (id == null) {
            student.setCreateTime(timeStamp);
            insert(student);
        } else {
            student.setId(id);
            if (getById(id) == null) {
                throw new RuntimeException("Student not found");
            } else {
                update(student);
            }
        }

        insert(student);

        return student.getId();
    }
}